package com.zut.base.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zut.base.common.entry.Pagination;
import com.zut.base.common.entry.Result;
import com.zut.base.common.entry.ResultCode;
import com.zut.base.common.entry.ResultVO;
import com.zut.base.common.util.CodeUtils;
import com.zut.base.common.util.RedisUtils;
import com.zut.base.common.util.StringUtils;
import com.zut.base.common.util.TokenUtils;
import com.zut.base.entity.Manager;
import com.zut.base.entity.Projectanduser;
import com.zut.base.entity.User;
import com.zut.base.mapper.UserMapper;
import com.zut.base.service.IManagerService;
import com.zut.base.service.IProjectanduserService;
import com.zut.base.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author yyl
 * @since 2021-03-31
 */
@RestController
@RequestMapping("/imp/user")
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @Autowired
    private IProjectanduserService projectanduserServiceImpl;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IManagerService managerServiceImpl;

    //手机验证码
    @GetMapping("/sendCode")
    public Object getCode(@NotNull String phone) {
        //发送验证码
        Map map = CodeUtils.sendPhoneCode(phone);
        //短信发送成功
        if (map.get("msg") == "OK") {
            //验证码1分钟失效
//            redisUtils.set(phone, "000000");
            redisUtils.set(phone, map.get("code"));
            return new ResultVO(200, "发送成功");
        }
        return new ResultVO(-9999, "发送失败");
    }

    //邮箱验证码
    @GetMapping("/sendEmailCode")
    public Object sendEmailCode(@Email String email) {
        //发送验证码
        Map map = CodeUtils.sendEmailCode(email);
        //短信发送成功
        if (map.containsKey("code")) {
            //验证码1分钟失效
            redisUtils.set(email, map.get("code"), 5 * 60);
            return new ResultVO(200, "发送成功");
        }
        return new ResultVO(-9999, "发送失败");
    }

    //登录(手机号+验证码)
    @PostMapping("/login/code")
    public Object LoginCode(@NotNull @RequestBody JSONObject oj) {
        String phone = oj.getString("phone");
        String captcha = oj.getString("captcha");
        Map map = new HashMap();
        String code = String.valueOf( redisUtils.get(phone));
        if (captcha.equals(code)) {
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("phone", phone);
            User user = userServiceImpl.getOne(queryWrapper);
            //首次登陆
            if (user == null) {
                //提示跳转至信息补全页面
                map.put("isFirst", "1");
            }
            //将用户信息存在redis中
            else {
                map.put("id", user.getId());
                map.put("isFirst", "-1");
                String token = TokenUtils.getToken(user);
                map.put("token", token);
            }
        } else {
            return new ResultVO(-9999, "验证码有误！");
        }
        return new ResultVO(map);
    }

    //信息补全
    @PostMapping("/completeMsg")
    public Object LoginCodes(@NotNull @RequestBody JSONObject oj) {
        String phone = oj.getString("phone");
        String email = oj.getString("email");
        String captcha = oj.getString("captcha");
        String password = oj.getString("password");
        String name = oj.getString("name");
        //校验验证码
        if (StringUtils.isNotEmpty(captcha) && !captcha.equals(String.valueOf(redisUtils.get(email)))) {
            return new ResultVO(-9999, "验证码有误！");
        }
        //判断邮箱或手机号是否已经注册过
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", phone).or().eq("email", email);
        User userMes = userServiceImpl.getOne(queryWrapper);
        if (userMes != null) return new ResultVO(-9999, "该邮箱已激活！请更换邮箱重新尝试！");
        //添加数据
        User user = new User();
        user.setName(name);
        user.setPhone(phone);
        user.setPassword(password);
        user.setEmail(email);
        user.setJob(oj.getString("job"));
        user.setOrganization(oj.getString("organization"));
        boolean rs = userServiceImpl.save(user);
        Map map = new HashMap();
        map.put("id", user.getId());
        if (rs) {
            String token = TokenUtils.getToken(user);
            map.put("token", token);
            return new ResultVO(map);
        }
        return new ResultVO(-9999, "信息补全失败，请重试！");
    }

    //退出登陆
//    @GetMapping("/exit")
//    public Object exit(){
//        Cookie cookie = new Cookie("token",null);
//        cookie.setMaxAge(0);//设置存活时间，“0”即马上消失
//        cookie.setPath("/");
//        response.addCookie(cookie);
//        return "退出成功!";
//    }

    //用户名密码登陆（手机号、邮箱）
    @PostMapping("/login/pass")
    public Object LoginPass(@RequestBody JSONObject oj) {
        String account = oj.getString("account");
        String password = oj.getString("password");
        QueryWrapper<User> userWrapper = new QueryWrapper();
        userWrapper.eq("password", password);
        userWrapper.and(wrapper -> wrapper.eq("phone", account).or().eq("email", account));
        User user = userServiceImpl.getOne(userWrapper);
        if (user == null) return new ResultVO(-9999, "用户名密码有误！");
        String token = TokenUtils.getToken(user);
        Map rs = new HashMap();
        rs.put("token", token);
        rs.put("id", user.getId());
        rs.put("code", 200);
        return new ResultVO(rs);
    }

//    //用户名密码登陆（手机号、邮箱）
//    @PostMapping("/login/pass")
//    public Object LoginPass(@RequestBody JSONObject oj) {
//        String account = oj.getString("account");
//        String password = oj.getString("password");
//        QueryWrapper<User> userWrapper = new QueryWrapper();
//        userWrapper.eq("password", password);
//        userWrapper.and(wrapper -> wrapper.eq("phone", account).or().eq("email", account));
//        User user = userServiceImpl.getOne(userWrapper);
//        Manager manager = null;
//        if (user == null) {
//            QueryWrapper<Manager> managerQueryWrapper = new QueryWrapper<>();
//            managerQueryWrapper.eq("account", account);
//            managerQueryWrapper.and(i->i.eq("password", password));
//            manager = managerServiceImpl.getOne(managerQueryWrapper);
//            if(manager==null) {
//                return new ResultVO(-9999, "用户名密码有误！");
//            }
//        }
//        String token = TokenUtils.getToken(user);
//        Map rs = new HashMap();
//        rs.put("token", token);
//        if(user == null) {
//            rs.put("id", user.getId());
//            rs.put("role", "user");
//        } else {
//            rs.put("id", manager.getId());
//            rs.put("role", "admin");
//        }
//        rs.put("code", 200);
//        return new ResultVO(rs);
//    }

    //id查用户信息
    @GetMapping("/getUserMesById")
    public Object getUserMesById(@NotNull String id) {
        User user = userServiceImpl.getById(id);
        if (user == null) return new ResultVO(-9999, "用户信息有误！");
        Map map = new HashMap();
        map.put("name", user.getName());
        map.put("head", user.getHead());
        map.put("organization", user.getOrganization());
        map.put("job", user.getJob());
        map.put("introduction", user.getIntroduction());
        map.put("phone", user.getPhone());
        map.put("email", user.getEmail());
        return new ResultVO(map);
    }

    //查该邮箱是否已注册
    @GetMapping("/emailIsRegister")
    public Object emailIsRegister(@Email String email) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        User user = userServiceImpl.getOne(wrapper);
        if (user != null) return "验证码已发送";
        return new ResultVO(-9999, "该邮箱尚未注册激活！");
    }

    //查手机号是否已注册
    @GetMapping("/phoneIsRegister")
    public Object phoneIsRegister(@Email String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        User user = userServiceImpl.getOne(wrapper);
        if (user == null) return "ok";
        return new ResultVO(-9999, "手机号已注册！");
    }

    //忘记密码
    @PostMapping("/forgetPass")
    public Object forgetPass(@RequestBody JSONObject oj) {
        String pass = oj.getString("password");
        String email = oj.getString("email");
        String captcha = oj.getString("captcha");
        //邮箱校验
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        User user = userServiceImpl.getOne(wrapper);
        if (user == null) return new ResultVO(-9999, "该邮箱尚未注册激活！");
        //验证码校验
        String code =String.valueOf(redisUtils.get(email));
        if (StringUtils.isEmpty(code) || !code.equals(captcha)) {
            return new ResultVO(-9999, "验证码有误！");
        }
        user.setPassword(pass);
        boolean save = userServiceImpl.saveOrUpdate(user);
        if (save) return "修改成功";
        return new ResultVO(-9999, "修改失败！");
    }


    //修改个人基本信息
    @PostMapping("modifyUserMes")
    public Object modifyUserMes(@RequestBody User user) {
        boolean rs = userServiceImpl.updateById(user);
        if (rs) return "修改成功";
        return new ResultVO(-9999, "修改失败！");

    }

    //修改密码
    @PostMapping("/modifyPass")
    public Object modifyPass(@RequestBody JSONObject oj) {
        String id = oj.getString("id");
        String oldPassword = oj.getString("oldPassword");
        String newPassword = oj.getString("newPassword");
        //校验
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id).eq("password",oldPassword);
        User user = userServiceImpl.getOne(wrapper);
        if(user == null) return new ResultVO<>(-9999,"密码有误！");
        user.setPassword(newPassword);
        boolean rs = userServiceImpl.updateById(user);
        if(!rs) return new ResultVO(-9999, "修改失败！");
        //重新生成token
        Map map = new HashMap();
        String token = TokenUtils.getToken(user);
        map.put("token", token);
        return new ResultVO<>(map);
    }

    //修改手机号
    @PostMapping("/modifyPhone")
    public Object modifyPhone(@RequestBody JSONObject oj){
        String phone = oj.getString("phone");
        String captcha = oj.getString("captcha");
        String code = String.valueOf(redisUtils.get(phone));
        if(StringUtils.isNotEmpty(code) && code.equals(captcha)){
            User user = new User();
            user.setId(oj.getString("id"));
            user.setPhone(phone);
            boolean rs = userServiceImpl.updateById(user);
            if(rs) return "修改成功";
            return new ResultVO<>(-9999,"更新失败！");
        }
        return new ResultVO<>(-9999,"验证码有误！");
    }
    //修改邮箱
    @PostMapping("/modifyEmail")
    public Object modifyEmail(@RequestBody JSONObject oj){
        String email = oj.getString("email");
        String captcha = oj.getString("captcha");
        String code = String.valueOf(redisUtils.get(email));
        if(StringUtils.isNotEmpty(code) && code.equals(captcha)){
            User user = new User();
            user.setId(oj.getString("id"));
            user.setEmail(email);
            boolean rs = userServiceImpl.updateById(user);
            if(rs) return "修改成功";
            return new ResultVO<>(-9999,"更新失败！");
        }
        return new ResultVO<>(-9999,"验证码有误！");
    }

    @PostMapping("/list/user")
    public Object listUser(@RequestBody JSONObject oj) {
        Integer current = 1;
        if(oj.getString("current")!=null && !oj.getString("current").equals("")) {
            current = Integer.parseInt(oj.getString("current"));
        }
        Integer size = 5;
        if(oj.getString("size")!=null && !oj.getString("size").equals("")) {
            size = Integer.parseInt(oj.getString("size"));
        }
        String search=oj.getString("search");
        //分页page对象
        IPage<User> iPage = new Page<>(current, size);
        //条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(search!=null && !search.equals("")) {
            queryWrapper.eq("isdeleted", 0);
            queryWrapper.like("email", search).or().like("name", search);
        }
        IPage<User> userPage = null;
        try {
            userPage = userServiceImpl.page(iPage, queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO<>(500, "查询异常");
        }
        Map<String, Object> map = new HashMap<>();
        if(userPage != null) {
            map.put("total", userPage.getTotal());
            if(userPage.getRecords().size()!=0) {
                map.put("list", userPage.getRecords());
            } else {
                map.put("list", new ArrayList<>());
            }
        } else {
            return new ResultVO<>(500, "查询异常");
        }
        return new ResultVO<>(200, "查询成功", map);
    }

    @PostMapping("/list/member")
    public Object listMember(@RequestBody JSONObject oj) {
        Integer current = 1;
        if(oj.getString("current")!=null && !oj.getString("current").equals("")) {
            current = Integer.parseInt(oj.getString("current"));
        }
        Integer size = 5;
        if(oj.getString("size")!=null && !oj.getString("size").equals("")) {
            size = Integer.parseInt(oj.getString("size"));
        }
        Pagination page = new Pagination(current, size);
        String search = oj.getString("search");
        Integer userId=null;
        if(oj.getString("userId")!=null && !oj.getString("userId").equals("")) {
            userId = Integer.parseInt(oj.getString("userId"));
        }
        Result<Projectanduser> result = null;
        Map<String, Object> map = new HashMap<>();
        try {
            result = userServiceImpl.findAllMemberByPage(page, search == null ? "" : search, userId);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new ResultVO<>(500, "查询异常");
        }
        List<Projectanduser> projectadnuserList = null;
        if(result != null) {
            if(result.getList()!=null || result.getList().size()!=0) {
                projectadnuserList = result.getList();
            } else {
                projectadnuserList = new ArrayList<>();
            }
            map.put("total", result.getNum()==null?0:result.getNum());
            map.put("list", projectadnuserList);
        }
        return new ResultVO<>(200, "查询成功", map);
    }

    @GetMapping("/remove")
    public Object removeUser(@NotNull String uid) {
        if(uid==null || "".equals(uid)) return new ResultVO<>(ResultCode.VALIDATE_FAILED, "请求参数校验失败");
        User user = userServiceImpl.getById(uid);
        if(user == null) return new ResultVO<>(ResultCode.FAILED, "不存在该用户");
        user.setIsdeleted("1");
        boolean flag = userServiceImpl.updateById(user);
        if(!flag) return new ResultVO<>(ResultCode.FAILED, "删除失败");
        Map<String, Object> map = new HashMap<>();
        map.put("status", "OK");
        return new ResultVO<>(200, "删除成功", map);
    }

    @GetMapping("/disable")
    public Object disableUser(@NotNull String uid) {
        if(uid==null || "".equals(uid)) return new ResultVO<>(ResultCode.VALIDATE_FAILED, "请求参数校验失败");
        User user = userServiceImpl.getById(uid);
        if(user == null) return new ResultVO<>(ResultCode.FAILED, "不存在该用户");
        user.setIsdisabled("1");
        boolean flag = userServiceImpl.updateById(user);
        if(!flag) return new ResultVO<>(ResultCode.FAILED, "禁用失败");
        Map<String, Object> map = new HashMap<>();
        map.put("status", "OK");
        return new ResultVO<>(200, "禁用成功", map);
    }

    @GetMapping("/cancel")
    public Object cancelDisable(@NotNull String uid) {
        if(uid==null || "".equals(uid)) return new ResultVO<>(ResultCode.VALIDATE_FAILED, "请求参数校验失败");
        User user = userServiceImpl.getById(uid);
        if(user == null) return new ResultVO<>(ResultCode.FAILED, "不存在该用户");
        user.setIsdisabled("0");
        boolean flag = userServiceImpl.updateById(user);
        if(!flag) return new ResultVO<>(ResultCode.FAILED, "恢复失败");
        Map<String, Object> map = new HashMap<>();
        map.put("status", "OK");
        return new ResultVO<>(200, "恢复成功", map);
    }

    @GetMapping("/member/remove")
    public Object removeMember(@NotNull String userId,@NotNull String projectId) {
        try {
            if(userId!=null && !userId.equals("")) {
                QueryWrapper<Projectanduser> proanduserWrapper = new QueryWrapper<>();
                proanduserWrapper.eq("userid", userId);
                proanduserWrapper.and(i->i.eq("projectid", projectId));
                projectanduserServiceImpl.remove(proanduserWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO<>(500, "删除异常");
        }
        return new ResultVO<>(200, "删除成功", "OK");
    }

}